using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;


namespace AppFiniteStateMachine
{
    [Serializable]
    public class Parameter
    {
    }
    
    public class FiniteStateMachineBase
    {
        public FiniteStateMachineBase(object initState=null)
        {
            if (initState != null)
                this.initState = initState.ToString();
        }
        
        // public Parameter parameter = null;
        
        public string initState;
        
        public IState currentState;

        public List<string> state_names = new List<string>();

        public Dictionary<string, IState> state_dc = new Dictionary<string, IState>();

        public string get_current_state()
        {
            var state_instance = currentState;
            string current_state = state_dc.FirstOrDefault(x => x.Value == state_instance).Key;
            return current_state;
        }

        public void Start()
        {
            BdUtils.assert(initState, $"initState 不能为空! initState: {initState}");
            TransitionState(initState);
        }

        public void Update()
        {
            if (currentState == null)
                return;
            currentState.OnUpdate();
        }

        public void TransitionState(object type)
        {
            string _type = BdUtils.conv_to_string(type);
            BdUtils.assert(_type, $"type 不能为空! type: {type}");
            BdUtils.assert(state_dc.ContainsKey(_type), $"type 不在 state_dc 中? type: {_type}, state_dc.keys: {BdUtils._log(state_dc.Keys)}");
            
            
            if (currentState != null)
                currentState.OnExit();
            
            currentState = state_dc[_type];
            BdUtils.assert(currentState, $"currentState 不能为空! type: {_type}");
            
            currentState.OnEnter();
        }

        public void init_attrs()
        {
            if (BdUtils.not_null(this.state_names))
            {
                this.initState = BdUtils.conv_to_bool(this.initState)? initState: this.state_names[0];
            }
        }

    }
}